package cn.ococci.dm.Main;

import android.net.wifi.ScanResult;
import android.os.SystemClock;

import com.alibaba.fastjson.JsonObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.ococci.dm.Base.ActivityStack;
import cn.ococci.dm.Base.BaseActivity;
import cn.ococci.dm.Base.BaseController;
import cn.ococci.dm.Main.Model.CurUser;
import cn.ococci.dm.Main.Model.DoorModel;
import cn.ococci.dm.Main.Model.DoorUnitModel;
import cn.ococci.dm.Main.Model.Ota;
import cn.ococci.dm.Main.Model.UnitModel;
import cn.ococci.dm.Main.Model.WifiObj;
import cn.ococci.dm.Main.Tools.DbTool;
import cn.ococci.dm.Main.Tools.FileTool;
import cn.ococci.dm.Main.Tools.LogTool;
import cn.ococci.dm.Main.Tools.StringTool;
import cn.ococci.dm.Main.Tools.ToastTool;
import cn.ococci.dm.Network.Http;
import cn.ococci.dm.Network.HttpCallback;
import cn.ococci.dm.Network.Urls;
import cn.ococci_dm.R;

/**
 * Created by cyan on 15/12/29.
 */
public class DoorBiz {

    /**
     * 获取门禁列表
     */
    public static void getDoorList(final HttpCallback<DoorModel> callback){

        RequestParams params = new RequestParams();
        params.put(Const.BuilderParams.company_id,""+ CurUser.getCompanyId());

        Http.get(Urls.getDoorListInfo,params,new Http(){

            @Override
            public void onSuccess(JsonObject json) {

                callback.onSuccessList(Convert.jsonToDoorList(json));
            }
        });

    }


    /**
     * 获取楼层单元
     */
    public static void getFloorList(final HttpCallback<UnitModel> callback){

        RequestParams params = new RequestParams();
        params.put(Const.BuilderParams.company_id,""+ CurUser.getCompanyId());

        Http.get(Urls.getUnitList,params,new Http(){

            @Override
            public void onSuccess(JsonObject json) {

                List<UnitModel> unitModelList = Convert.jsonToUnitList(json);
                if(callback != null){
                    callback.onSuccessList(unitModelList);
                }

            }
        });
    }


    /**
     * 设置
     * @param isBack 后台请求
     * @param doorModel
     * @param callback
     */
    public static void setDoorInfo(final boolean isBack,final DoorModel doorModel, final HttpCallback<DoorModel> callback){

        RequestParams params = new RequestParams();
        params.put(Const.BuilderParams.door_Bssid,doorModel.getDoorMac());
        params.put(Const.BuilderParams.longitude,""+doorModel.getLongitude());
        params.put(Const.BuilderParams.latitude,""+doorModel.getLatitude());
        params.put(Const.BuilderParams.name,doorModel.getDoorName());
        params.put(Const.BuilderParams.company_id,""+CurUser.getCompanyId());
        params.put(Const.BuilderParams.ssid,doorModel.getWifiName());

        LogTool.log(LogTool.CYAN,"请求参数:"+params.toString());

        Http http = new Http(ActivityStack.currentActivity()){

            @Override
            public void onSuccess(JsonObject json) {

                doorModel.setDoorId(json.getLongValue(Const.BuilderParams.door_id));

                doorModel.setLocalId(0);
                doorModel.setSyn(0);
                doorModel.update(doorModel.getId());

                callback.onSuccess(doorModel);

            }

            @Override
            public void onFailure(int code, String msg) {
                callback.onFailure(code,msg);
            }
        };

        if (isBack){
            http.turnToBack();
        }

        Http.post(Urls.setDoorInfo,params,http);

    }


    /**
     * 上传门禁单元列表
     * @param isBack
     * @param doorId
     * @param doorUnitModels
     */
    public static void setDoorPermission(final boolean isBack, long doorId, final List<DoorUnitModel> doorUnitModels,final HttpCallback callback){

        RequestParams params = new RequestParams();
        params.put(Const.BuilderParams.door_id,""+doorId);
        params.put(Const.BuilderParams.unit_code, StringTool.builderUnitCode(doorUnitModels));

        LogTool.log(LogTool.CYAN,"请求参数:"+params.toString());

        Http http = new Http(ActivityStack.currentActivity()) {

            @Override
            public void onSuccess(JsonObject json) {

                DataSupport.deleteAll(DoorUnitModel.class,"doorLocalId = ?",""+doorUnitModels.get(0).getDoorLocalId());
                callback.onSuccess(json);
            }

            @Override
            public void onFailure(int code, String msg) {
                if (!isBack){
                    ToastTool.showOnUiThread(R.string.upload_unit_title);
                }
            }
        };

        if (isBack){
            http.turnToBack();
        }

        Http.post(Urls.setDoorPermission,params,http);

    }


    /**
     * 上传门禁周边Wifi
     * @param data
     */
    public static void uploadDeviceRoundWifi(List<WifiObj> data) {

        if (!StringTool.hasData(data)){
            LogTool.log(LogTool.CYAN,"没有需要上传的WiFi");
            return;
        }

        RequestParams p = Convert.wifiListDataToParams(data);

        LogTool.log(LogTool.CYAN,"上传周边WiFi参数:"+p.toString());

        Http.post(Urls.deviceDoorSurroundWifiList, p, new Http() {

            @Override
            public void onSuccess(JsonObject json) {

                LogTool.log(LogTool.CYAN, "上传成功");
                DataSupport.deleteAll(WifiObj.class, "companyId = ?", "0");

            }

            @Override
            public void onFailure(int code, String msg) {
                LogTool.log(LogTool.CYAN, "上传失败");

            }
        });

    }


    /**
     * 生成并且保存Wifi扫描的结果
     * @param scanResultList
     * @param doorWifiBSSid
     * @return
     */
    public static List<WifiObj> returnOrSaveWifiObjListData(List<ScanResult> scanResultList, String doorWifiBSSid){

        List<WifiObj> data = new ArrayList<>(scanResultList.size());
        for(ScanResult result:scanResultList){

            WifiObj obj = new WifiObj();
            obj.setSsid(StringTool.replaceDoubleQuotationMarks(result.SSID));
            obj.setBssid(StringTool.replaceDoubleQuotationMarks(result.BSSID));
            obj.setLevel(result.level);
            obj.setDoorBssid(doorWifiBSSid);

            data.add(obj);
        }
        return  data;
    }

    /**
     * 获取云端上的OTA 升级信息(和本地数据库中的版本做一个比较)
     * @param bc
     */
    public static void getOtaVersionListInfo(final BaseController bc){

        Http http = new Http(bc){

            @Override
            public void onSuccess(JsonObject json) {
                List<Ota> curList = Convert.jsonToOatList(json);

                if(!StringTool.hasData(curList)){
                    LogTool.log(LogTool.CYAN,"获取不到需要更新的固件版本信息");
                    return;
                }

                for(Ota curOta:curList){

                    Ota tmp = DbTool.findOTA(curOta.getOtaType());

                    if(tmp == null || StringTool.compareVersion(tmp.getVersion(),curOta.getVersion())){
                        downOTA(bc.getBaseActivity(),curOta,tmp);
                    }
                    SystemClock.sleep(200);
                }
            }
        };
        http.turnToBack();
        Http.post(Urls.ota_versionInfo,new RequestParams(),http);

    }


    private static void downOTA(BaseActivity activity,final Ota curOta,final Ota dbOta){

        new AsyncHttpClient().get(curOta.getUrl(),new RequestParams(),new FileAsyncHttpResponseHandler(activity){

            @Override
            public void onSuccess(int statusCode, Header[] headers, File file) {

                if(!curOta.getMd5().equals(FileTool.getMD5(file))){
                    LogTool.log(LogTool.CYAN,"MD5不匹配，下载文件出错");
//                    return;
                }

                LogTool.log(LogTool.CYAN,"下载成功" +curOta.getOtaType() );
                FileTool.createOTADirectory();

                // 删除之前下载的文件类型.
                String delPath = FileTool.getOtaPath() +((curOta.getOtaType() == OtaType.OTC_AP.type) ? Const.OTA_AP_NAME:Const.OTA_PR_NAME);
                FileTool.deleteFile(delPath);

                // cp
                FileTool.copyFile(file,new File(delPath));

                //更新或者保存数据
                if( dbOta != null && dbOta.getOtaType() != 0){
                    dbOta.delete();
                }
                curOta.save();
            }

            @Override
            public void onFailure(int statusCode, Throwable e, File response) {
                LogTool.log(LogTool.CYAN,"下载错误码:"+statusCode + ",错误信息:" + e.toString());
            }
        });
    }



}
